package com.linkoog.devtools.intellij.ui.table.column_info.column;

import com.linkoog.devtools.intellij.ui.table.cell_editor.ComboBoxTableCellEditor;
import com.linkoog.devtools.intellij.ui.table.cell_reander.JComboBoxEnumTableCellRenderer;
import com.linkoog.devtools.intellij.ui.table.TableRowData;
import com.linkoog.devtools.intellij.ui.table.column_info.provider.TableCellValueGetterProvider;
import com.linkoog.devtools.intellij.ui.table.column_info.provider.getter.FieldTableCellValueGetterProvider;
import com.linkoog.devtools.intellij.ui.table.column_info.provider.setter.FieldTableCellValueSetterProvider;
import org.jetbrains.annotations.Nullable;

import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.lang.reflect.Field;

public class ComboBoxEnumColumnInfo<T extends TableRowData, E extends Enum<E>> extends AbstractColumnInfo<T, E> {

    private String columnName;
    private String fieldName;

    TableCellValueGetterProvider<T> tableCellValueGetterProvider;
    FieldTableCellValueSetterProvider<T> tableCellValueSetterProvider;

    public ComboBoxEnumColumnInfo(String columnName, String fieldName) {
        super(columnName);
        this.columnName = columnName;
        this.fieldName = fieldName;
        tableCellValueGetterProvider = new FieldTableCellValueGetterProvider<>(fieldName);
        tableCellValueSetterProvider = new FieldTableCellValueSetterProvider<>(fieldName);
    }

    @Nullable
    @Override
    public E valueOf(T rowData) {
        return (E) tableCellValueGetterProvider.valueOf(rowData);
    }

    @Override
    public void setValue(T rowData, E value) {
        tableCellValueSetterProvider.setValue(rowData, value);
    }


    @Override
    public boolean isCellEditable(final T rowData) {
        return true;
    }

    @Override
    public @Nullable TableCellEditor getEditor(T rowData) {
        try {
            Field declaredField = rowData.getClass().getDeclaredField(fieldName);
            return new ComboBoxTableCellEditor((Class<? extends Enum>) declaredField.getType());
        } catch (Exception e) {
            return null;
        }

    }

    @Override
    public @Nullable TableCellRenderer getRenderer(T rowData) {
        return JComboBoxEnumTableCellRenderer.INSTANCE;
    }
}
